package com.zp.self.module.工具.文件复制;

import java.io.*;
import java.nio.channels.FileChannel;

/**
 * @author ：by peng.zeng
 * @date ：Created 2021/8/10 18:37
 * @description ：文件复制，解除加锁的问题
 */
public class CopyFile {

    public static void main(String[] agrs) throws IOException {


        BufferedReader in1 = new BufferedReader(new FileReader("C:\\Users\\peng.zeng\\Desktop\\exportexcel\\test.json"));
        BufferedWriter out1 = new BufferedWriter(new FileWriter("C:\\Users\\peng.zeng\\Desktop\\exportexcel\\test_cp.json"));
        String str;
        int row = 0;
        while ((str = in1.readLine()) != null) {
            if(row!=0){
                out1.write(str);
            }
            System.out.println("读取到: "+row+++" 行");
        }
        in1.close();
    }

    private static void moveFile() {
        try {
            File file = new File("C:\\Users\\peng.zeng\\Desktop\\exportexcel\\0210860000021.json");

            if (file.renameTo(new File("C:\\Users\\peng.zeng\\Desktop\\exportexcel\\" + "0210860000021_cp.json"))) //源文件移动至目标文件目录
            {
                System.out.println("File is moved successful!");//输出移动成功
            } else {
                System.out.println("File is failed to move !");//输出移动失败
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void copyNio() throws IOException {
        FileChannel input = null;
        FileChannel output = null;
        try {
            input = new FileInputStream(new File("C:\\Users\\peng.zeng\\Desktop\\exportexcel\\0210860000021.json")).getChannel();
            output = new FileOutputStream(new File("C:\\Users\\peng.zeng\\Desktop\\exportexcel\\0210860000021_cp.json")).getChannel();
            output.transferFrom(input, 200, input.size());
        } catch (Exception e) {
            System.out.println(e.fillInStackTrace().getMessage());
        } finally {
            assert input != null;
            input.close();
            assert output != null;
            output.close();
        }
    }
}
